// pages/index/index.js
const app = getApp();

Page({
  data: {
    currentEvent: null,
    userInfo: null,
    statistics: null,
    safetyStatus: 'SAFE',
    supportRequested: false,
    location: '获取中...',
    lastLocationUpdate: '-',
    loading: false,
    refreshing: false
  },

  onLoad() {
    console.log('主页加载');
    this.checkAuth();
    this.loadUserInfo();
    this.loadCurrentEvent();
    this.loadStatistics();
    this.getCurrentLocation();
  },

  onShow() {
    console.log('主页显示');
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  // 检查认证状态
  checkAuth() {
    if (!app.globalData.token || !app.globalData.userInfo) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 刷新数据
  async refreshData() {
    this.setData({ refreshing: true });
    
    try {
      await Promise.all([
        this.loadCurrentEvent(),
        this.loadStatistics(),
        this.getCurrentLocation()
      ]);
    } catch (error) {
      console.error('刷新数据失败:', error);
    } finally {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = app.globalData.userInfo;
    if (userInfo) {
    this.setData({
        userInfo: userInfo
    });
    }
  },

  // 加载当前任务
  async loadCurrentEvent() {
    try {
      const res = await app.request({
      url: '/api/events/my-current-event',
      method: 'GET'
      });

      if (res.data && res.data.id) {
        this.setData({
          currentEvent: res.data
        });
        app.globalData.currentEvent = res.data;
        
        // 更新安全状态和支援请求状态
        this.setData({
          safetyStatus: res.data.safetyStatus || 'SAFE',
          supportRequested: res.data.supportRequested || false
        });
      } else {
        this.setData({
          currentEvent: null
        });
        app.globalData.currentEvent = null;
      }
    } catch (err) {
      console.error('加载当前任务失败:', err);
      this.setData({
        currentEvent: null
    });
    }
  },

  // 加载统计信息
  async loadStatistics() {
    try {
      const res = await app.request({
      url: '/api/events/my-statistics',
      method: 'GET'
      });

      this.setData({
        statistics: res.data
      });
    } catch (err) {
      console.error('加载统计信息失败:', err);
    }
  },

  // 获取当前位置
  async getCurrentLocation() {
    try {
      const res = await new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
          success: resolve,
          fail: reject
        });
      });

        this.setData({
          location: `${res.latitude.toFixed(4)}, ${res.longitude.toFixed(4)}`,
          lastLocationUpdate: new Date().toLocaleTimeString('zh-CN')
        });

      // 更新全局位置信息
      app.globalData.currentLocation = {
        latitude: res.latitude,
        longitude: res.longitude,
        timestamp: new Date().getTime()
      };
    } catch (err) {
        this.setData({
          location: '获取失败',
          lastLocationUpdate: '-'
        });
        console.error('获取位置失败:', err);
      }
  },

  // 接受任务
  async acceptEvent() {
    const { currentEvent } = this.data;
    if (!currentEvent) {
      app.showError('没有可接受的任务');
      return;
    }

    const confirmed = await app.showConfirm('确认接受', '确认接受此任务？');
    if (confirmed) {
      await this.updateEventStatus('accept');
        }
  },

  // 开始前往
  async startEnRoute() {
    const confirmed = await app.showConfirm('确认前往', '确认开始前往现场？');
    if (confirmed) {
      await this.updateEventStatus('en-route');
        }
  },

  // 到达现场
  async arriveAtScene() {
    const confirmed = await app.showConfirm('确认到达', '确认已到达现场？');
    if (confirmed) {
      await this.updateEventStatus('arrive');
        }
  },

  // 开始处理
  async startProcessing() {
    const confirmed = await app.showConfirm('确认处理', '确认开始处理任务？');
    if (confirmed) {
      await this.updateEventStatus('start-processing');
        }
  },

  // 完成任务
  async completeTask() {
    const { currentEvent } = this.data;
    if (!currentEvent) {
      app.showError('没有可完成的任务');
      return;
    }

    const result = await new Promise((resolve) => {
    wx.showModal({
      title: '完成任务',
      content: '请输入完成说明',
      editable: true,
      success: (res) => {
        if (res.confirm) {
            resolve(res.content);
          } else {
            resolve(null);
          }
        }
      });
    });

    if (result !== null) {
      await this.updateEventStatus('complete', result);
    }
  },

  // 更新任务状态
  async updateEventStatus(action, notes = '') {
    const { currentEvent } = this.data;
    if (!currentEvent) return;

    this.setData({ loading: true });
    app.showLoading('更新中...');

    try {
    let url = '';
    let data = {};

    switch (action) {
      case 'accept':
        url = `/api/events/${currentEvent.id}/accept`;
        break;
      case 'en-route':
        url = `/api/events/${currentEvent.id}/en-route`;
          data = { 
            latitude: app.globalData.currentLocation?.latitude || 0, 
            longitude: app.globalData.currentLocation?.longitude || 0 
          };
        break;
      case 'arrive':
        url = `/api/events/${currentEvent.id}/arrive`;
          data = { 
            latitude: app.globalData.currentLocation?.latitude || 0, 
            longitude: app.globalData.currentLocation?.longitude || 0 
          };
        break;
      case 'start-processing':
        url = `/api/events/${currentEvent.id}/start-processing`;
        break;
      case 'complete':
        url = `/api/events/${currentEvent.id}/complete`;
        data = { completionNotes: notes };
        break;
    }

      const res = await app.request({
      url: url,
      method: 'POST',
      data: data
      });

      if (res.data.success) {
        app.showSuccess('操作成功');
        // 刷新当前任务
        await this.loadCurrentEvent();
      } else {
        app.showError(res.data.message || '操作失败');
      }
    } catch (err) {
      console.error('更新任务状态失败:', err);
      app.showError('操作失败，请重试');
    } finally {
      this.setData({ loading: false });
      app.hideLoading();
    }
  },

  // 更新安全状态
  async updateSafetyStatus(e) {
    const status = e.detail.value;
    const { currentEvent } = this.data;
    
    if (!currentEvent) {
      app.showError('没有当前任务');
      return;
    }
    
    try {
      const res = await app.request({
      url: `/api/events/${currentEvent.id}/safety-status`,
      method: 'POST',
        data: {
          status: status
        }
      });

      // 后端返回的是Event对象，不是包含success字段的响应
      if (res.statusCode === 200) {
      this.setData({
          safetyStatus: status,
          currentEvent: res.data // 更新当前任务信息
        });
        app.showSuccess('安全状态已更新');
      } else {
        app.showError('更新失败');
      }
    } catch (err) {
      console.error('更新安全状态失败:', err);
      app.showError('更新失败，请重试');
    }
  },

  // 发送SOS
  async sendSOS() {
    const confirmed = await app.showConfirm('发送SOS', '确认发送紧急求助信号？');
    if (!confirmed) return;

    const { currentEvent } = this.data;
    if (!currentEvent) {
      app.showError('没有当前任务');
      return;
    }

    this.setData({ loading: true });
    app.showLoading('发送中...');

    try {
      const res = await app.request({
            url: `/api/events/${currentEvent.id}/sos`,
            method: 'POST',
        data: {
          message: '紧急求助',
          latitude: app.globalData.currentLocation?.latitude || 0,
          longitude: app.globalData.currentLocation?.longitude || 0
        }
      });

      if (res.statusCode === 200) {
            this.setData({
          safetyStatus: 'SOS',
          currentEvent: res.data // 更新当前任务信息
        });
        app.showSuccess('SOS信号已发送');
      } else {
        app.showError('发送失败');
      }
    } catch (err) {
      console.error('发送SOS失败:', err);
      app.showError('发送失败，请重试');
    } finally {
      this.setData({ loading: false });
      app.hideLoading();
        }
  },

  // 请求支援
  async requestSupport() {
    const confirmed = await app.showConfirm('请求支援', '确认请求支援？');
    if (!confirmed) return;

    const { currentEvent } = this.data;
    if (!currentEvent) {
      app.showError('没有当前任务');
      return;
    }

    this.setData({ loading: true });
    app.showLoading('请求中...');

    try {
      const res = await app.request({
                url: `/api/events/${currentEvent.id}/request-support`,
                method: 'POST',
                data: {
          supportType: 'GENERAL',
          description: '需要支援',
          latitude: app.globalData.currentLocation?.latitude || 0,
          longitude: app.globalData.currentLocation?.longitude || 0
                }
      });

      if (res.statusCode === 200) {
                this.setData({
          supportRequested: true,
          currentEvent: res.data // 更新当前任务信息
        });
        app.showSuccess('支援请求已发送');
      } else {
        app.showError('请求失败');
      }
    } catch (err) {
      console.error('请求支援失败:', err);
      app.showError('请求失败，请重试');
    } finally {
      this.setData({ loading: false });
      app.hideLoading();
            }
  },

  // 取消支援
  async cancelSupport() {
    const confirmed = await app.showConfirm('取消支援', '确认取消支援请求？');
    if (!confirmed) return;

    this.setData({ loading: true });
    app.showLoading('取消中...');

    try {
      const res = await app.request({
        url: '/api/events/cancel-support',
            method: 'POST'
      });

      if (res.data.success) {
            this.setData({
              supportRequested: false
            });
        app.showSuccess('支援请求已取消');
      } else {
        app.showError(res.data.message || '取消失败');
      }
    } catch (err) {
      console.error('取消支援失败:', err);
      app.showError('取消失败，请重试');
    } finally {
      this.setData({ loading: false });
      app.hideLoading();
        }
  },

  // 刷新位置
  async refreshLocation() {
    await this.getCurrentLocation();
    app.showSuccess('位置已更新');
  },

  // 查看任务详情
  viewEventDetail() {
    const { currentEvent } = this.data;
    if (currentEvent) {
      wx.navigateTo({
        url: `/pages/task/task?id=${currentEvent.id}`
      });
    }
  },

  // 查看统计详情
  viewStatistics() {
    wx.switchTab({
      url: '/pages/statistics/statistics'
    });
  }
}); 